package com.mutual.assistance.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mutual.assistance.auth.mapper.UserMapper;
import com.mutual.assistance.auth.model.po.UserPO;
import com.mutual.assistance.auth.model.vo.AuthParamsVO;
import com.mutual.assistance.auth.service.AuthService;
import com.mutual.assistance.exception.BizException;
import com.mutual.assistance.exception.code.ExceptionCode;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author chenyuxin
 * @version 1.0
 * @description 账号密码认证及验证码验证
 * @date 2023/4/15 19:26
 */
@Service("password_authService")
public class PasswordAuthServiceImpl implements AuthService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public UserPO execute(AuthParamsVO authParamsVO) {
        // 校验账号是否存在
        String username = authParamsVO.getUsername();
        UserPO userPO = userMapper.selectOne(new LambdaQueryWrapper<UserPO>().eq(UserPO::getUsername, username));
        if (userPO == null) {
            throw new BizException(ExceptionCode.ILLE_GALA_ARGUMENT_EX.getCode(), "用户账号不存在");
        }

        // 开始比对密码
        String password = authParamsVO.getPassword();
        String passwordDB = userPO.getPassword();
        boolean matches = passwordEncoder.matches(password, passwordDB);
        if (!matches) {
            throw new BizException(ExceptionCode.ILLE_GALA_ARGUMENT_EX.getCode(), "账号或者密码不正确");
        }
        return userPO;
    }
}
